package com.jn.mvvm2.views;

import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.jn.mvvm2.R;
import com.jn.mvvm2.base.BaseActivity;
import com.jn.mvvm2.databinding.ActivityIdiomBinding;
import com.jn.mvvm2.entity.Idiom;
import com.jn.mvvm2.viewmodel.IdiomViewModel;

public class IdiomActivity extends BaseActivity<ActivityIdiomBinding> {

    private IdiomViewModel mIdiomViewModel;
    private LiveData<Idiom> mIdiomLiveData;
    private String mCurrentAnswer;

    @Override
    public int getLayoutId() {
        return R.layout.activity_idiom;
    }

    @Override
    public void init() {
        mIdiomViewModel = new ViewModelProvider(this).get(IdiomViewModel.class);
        mIdiomLiveData = mIdiomViewModel.getLiveData();
        mIdiomLiveData.observe(this, new Observer<Idiom>() {
            @Override
            public void onChanged(Idiom idiom) {
                Glide.with(IdiomActivity.this).load(idiom.getImg()).into(mBinding.image);
                mCurrentAnswer = idiom.getAnswer();
            }
        });
        mBinding.setListener(new ButtonClickListener());
        mIdiomViewModel.getData();
    }

    public class ButtonClickListener {
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.button) {
                String answer = mBinding.edit.getText().toString();
                if (!TextUtils.isEmpty(answer) && !TextUtils.isEmpty(mCurrentAnswer)) {
                    if (answer.equals(mCurrentAnswer)) {
                        showToast("回答正确!");
                        mBinding.text.setText("");
                        mIdiomViewModel.getData();
                    } else {
                        showToast("回答错误!");
                    }
                    mBinding.edit.setText("");
                }
            } else if (id == R.id.button1) {
                mIdiomViewModel.getData();
                mBinding.edit.setText("");
                mBinding.text.setText("");
            } else if (id == R.id.button2) {
                if (mCurrentAnswer != null) {
                    mBinding.text.setText(mCurrentAnswer);
                }
            }
        }
    }
}
